package com.young.dubbo.protocol.dubbo;


import com.young.dubbo.framework.Invocation;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * 继承ChannelInboundHandlerAdapter，用于处理客户端发送过来的请求
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    private ChannelHandlerContext context;
    private Invocation invocation;
    private String result;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    /**
     * 处理服务端向客户端返回的数据，并唤醒当前线程
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
        System.out.println("接收到服务器返回的数据，唤醒线程......");
        notify();
    }

    /**
     * 线程池自动调用，向服务端发送数据，并阻塞等待服务端返回数据
     * @return
     * @throws InterruptedException
     */
    public synchronized Object call() throws InterruptedException {
        context.writeAndFlush(this.invocation);
        System.out.println("休眠线程,等待服务器返回结果......");
        wait();
        return result;
    }

    public void setInvocation(Invocation invocation){
        this.invocation = invocation;
    }


}
